/*
 * @Author: 郑子胜(Zechariahzheng)
 * @Date: 2023-12-06 14:37:49
 * @LastEditors: 郑子胜(Zechariahzheng)
 * @LastEditTime: 2023-12-12 17:16:56
 * @Descripttion: 
 */
#include "WxConfig.h"

#define HOST_NAME  "bemfa"
#define MAGIC_NUMBER 0xAA

void setConfig(){
    String mac = WiFi.macAddress().substring(8);//取mac地址做主题用
    mac.replace(":", "");//去掉:号
    WiFiClient client_bemfa_WiFiClient;
    HTTPClient http_bemfa_HTTPClient;
    http_bemfa_HTTPClient.begin(client_bemfa_WiFiClient,"http://pro.bemfa.com/vv/setSmartConfig?version=1&user="+mac);
    int httpCode = http_bemfa_HTTPClient.GET();
    if (httpCode == 200) {
      WX_DEBUG_PRINTLN("wifi smartconfig ok");
    }
    http_bemfa_HTTPClient.end();
}

void WxConfig::init() {
  this->config_flag = 0;
  loadConfig();
  waitKey();
  initWiFi();
}

/**
* 加载存储的信息，并检查是否进行了反复5次重启恢复出厂信息
*/
// void WxConfig::loadConfig() {
//   uint8_t *p = (uint8_t*)(&config);
//   uint8_t mac[6];
//   WiFi.macAddress(mac);
//   EEPROM.begin(512);
//   for (int i = 0; i < sizeof(config); i++)
//     {
//     *(p + i) = EEPROM.read(i);
//   }
//   config.reboot = config.reboot + 1;
//   if(config.reboot>=4){
//       restoreFactory();
//   }
//   if(config.magic != 0xAA){
//     config_flag = 1;
//   }
//   EEPROM.begin(512);
//   for (int i = 0; i < sizeof(config); i++){
//     EEPROM.write(i, *(p + i));
//   }
//   EEPROM.commit();
//   delay(2000);
//   EEPROM.begin(512);
//   config.reboot = 0;
//   for (int i = 0; i < sizeof(config); i++){
//     EEPROM.write(i, *(p + i));
//   }
//   EEPROM.commit();
//   delay(2000);
// }

/**
* 加载存储的信息，并检查存储信息是否可用
*/
void WxConfig::loadConfig() {
  uint8_t *p = (uint8_t*)(&config);
  uint8_t mac[6];
  WiFi.macAddress(mac);
  EEPROM.begin(512);
  for (int i = 0; i < sizeof(config); i++)
    {
    *(p + i) = EEPROM.read(i);
  }
  char temp[32];
  sprintf(temp, "%s_%02X%02X%02X", HOST_NAME, mac[3], mac[4], mac[5]);
  WiFi.hostname(temp);
  if(WiFi.status() != WL_CONNECTED){
    WiFi.disconnect();//断开连接
    WiFi.mode(WIFI_STA);//STA模式
    WiFi.begin(config.stassid, config.stapsw);//连接路由器
  }
  config_flag = 1;
  for (int i = 0; i < 20; i++) {
    delay(1000);
    if (WiFi.status() != WL_CONNECTED) {
      WX_DEBUG_PRINT(".");
    } else {
      WX_DEBUG_PRINTLN("connected!");
      config_flag = 0;
      break;
    }
  }
}

/**
* 检查是否需要airkiss配网
*/
void WxConfig::waitKey() {
  if(config_flag == 1){
    doSmartconfig();
  }
}

/**
* 初始化wifi信息，并连接路由器网络
*/
void WxConfig::initWiFi(){
  char temp[32];
  uint8_t mac[6];
  WiFi.macAddress(mac);
  sprintf(temp, "%s_%02X%02X%02X", HOST_NAME, mac[3], mac[4], mac[5]);
  WiFi.hostname(temp);
  if(WiFi.status() != WL_CONNECTED){
    WiFi.disconnect();//断开连接
    WiFi.mode(WIFI_STA);//STA模式
    WiFi.begin(config.stassid, config.stapsw);//连接路由器
  }
  while (WiFi.status() != WL_CONNECTED) {//检查是否连接成功
    delay(500);
    WX_DEBUG_PRINT(".");
  }
  if(config_flag == 1){
    setConfig();
  }
  WX_DEBUG_PRINTLN("wifi config ok");
  WX_DEBUG_PRINT("local ip is: ");
  WX_DEBUG_PRINTLN(WiFi.localIP());
  WiFi.softAP(temp);
}

/**
* 恢复出厂设置，清除存储的wifi信息
*/
void WxConfig::restoreFactory() {
  WX_DEBUG_PRINTLN("Restore Factory....... ");
  config.magic = 0x00;
  strcpy(config.stassid, "");
  strcpy(config.stapsw, "");
  config.magic = 0x00;
  saveConfig();
  delayRestart(1);
  while (1) {
      delay(100);
  }
}

/**
* 存储配网信息
*/
void WxConfig::saveConfig(){
  uint8_t mac[6];
  WiFi.macAddress(mac);
  config.reboot = 0;
  EEPROM.begin(512);
  uint8_t *p = (uint8_t*)(&config);
  for (int i = 0; i < sizeof(config); i++)
  {
    EEPROM.write(i, *(p + i));
  }
  EEPROM.commit();
 }

/**
 * 重启
*/
void WxConfig::delayRestart(float t) {
  delayTimer.attach(t, []() {
    ESP.restart();
  });
}

/**
* airkiss配网
*/
void WxConfig::doSmartconfig() {
  WX_DEBUG_PRINTLN(" Smartconfig begin,Waiting for WeChat Config.....");
  WiFi.mode(WIFI_STA);
  WiFi.stopSmartConfig();
  WiFi.beginSmartConfig();
  int cnt = 0;
  bool flag_ok = false;
  while (!WiFi.smartConfigDone()) {
    delay(300);
    if (flag_ok == true) continue;
    if (WiFi.smartConfigDone()) {
        strcpy(config.stassid, WiFi.SSID().c_str());
        strcpy(config.stapsw, WiFi.psk().c_str());
        config.magic = 0xAA;
        saveConfig();
        flag_ok = true;
        
    }
    cnt++;
    if (cnt >= 600) {
      delayRestart(0);
    }
  }
}

